// 基础库
function hasClass(elem, cls) {
    cls = cls || '';
    if (cls.replace(/\s/g, '').length == 0) return false; //当cls没有参数时，返回false
    return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
}

function addClass(elem, cls) {
    if (!hasClass(elem, cls)) {
        elem.className = elem.className == '' ? cls : elem.className + ' ' + cls;
    }
}

function removeClass(elem, cls) {
    if (hasClass(elem, cls)) {
        var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, '') + ' ';
        while (newClass.indexOf(' ' + cls + ' ') >= 0) {
            newClass = newClass.replace(' ' + cls + ' ', ' ');
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    }
}

//gobal variable 
//var formNode = document.getElementsByTagName('form')[0];
// 图片相关
var g_uploadNum = 0;
var e_maxUpload = 2;

var validateStatusNew = {
    idcard_sn: false,
    // bank_card_sn: false,
};
var validateStatusMod = {
    bank_card_username: false,
    idcard_sn: false,
    bank_card_sn: false,
}
var validateStatus = g_page === 'newCard' ? validateStatusNew : validateStatusMod;

//init 初始化状态
document.getElementById('idNo').value = "";
//focus 滚动上面  方便手机输入
document.getElementById('idNo').onfocus = function () {
    window.scroll(0, document.documentElement.scrollHeight);
}
document.getElementById('idNo').onkeyup = function () {
    toggleShowCancelBut(this.value);
}


function isValidateSelect() {
    var elem = document.getElementById('branch_select');
    var item = elem;
    if (item.selectedIndex === 0) {
        return false
    }
    /*
     var elems = document.getElementsByTagName('select');
     var i, len=elems.length, item;
     for(i=0; i<len; i++) {
     item = elems[i];
     // 如果没有选择 立即返回false ,
     // 第一个项为 请选择...
     if( item.selectedIndex === 0) {
     return false
     }
     }
     */
    return true;
}


// 查询除exceptKey外所有的检验情况
// false 为不通过, true为通过
// function isValidate(exceptKey) {
//     if (g_uploadNum < e_maxUpload) {
//         return false
//     }
//     var key, item;
//     for (key in validateStatus) {
//         if (key === exceptKey) {
//             continue;
//         }
//         if (!validateStatus[key]) {
//             return false
//         }
//     }
//     //
//     if (g_page === 'modCard') {
//         if (!isValidateSelect()) {
//             return false;
//         }
//     }
//
//     return true;
// }

function isNotValidate() {
    if (g_page === 'modCard') {
        var cardOwner = document.getElementById('cardOwner');
        if (cardOwner.value === "") {
            return "持卡人不能为空";
        }

        var bankNo = document.getElementById('bank_card');
        if (bankNo.value === "") {
            return "银行卡号不能拿为空";
        }

        if (!isRealBankCard) {
            return "请输入正确的银行卡号";
        }

        var branchKey = document.getElementById('branch_select');
        if (branchKey.selectedIndex === 0) {
            return "请选择支行";
        }
    }

    var idNo = document.getElementById('idNo');
    if (idNo.value === "") {
        return "身份证号码不能为空";
    }

    if (g_uploadNum < e_maxUpload) {
        return '需要上传两张图片'
    }

    return false;
}
// function toggleSubmitStatus(enable) {
//     if (enable) {
//         if (!(typeof(isRealBankCard) == "undefined") && !isRealBankCard) {
//             return false;
//         }
//     }
//     var submitBut = document.getElementsByClassName('submit')[0];
//     submitBut.disabled = !enable;
// }


// 省市联动绑定
//$('#distpicker').distpicker({
//autoSelect: false
//});

// 绑定事件
// 绑定select 标签修改事件
function bindSelect() {
    var selectElems = document.getElementsByTagName('select');
    var i = 0, elem;
    var len = selectElems.length;
    for (i = 0; i < len; i++) {
        elem = selectElems[i];
        elem.onchange = function (e) {
            //remove tips class
            removeClass(this, 'tips');
            var name = this.name;
            // 更新提交状态
            // if (isValidate()) {
            //     toggleSubmitStatus(true);
            // }
        }
    }
}
bindSelect();

//显示清除身份证按钮
function toggleShowCancelBut(value) {
    var but = document.getElementById('idNo-cancel-but');
    if (value === "") {
        but.style.display = 'none';
    } else {
        but.style.display = 'initial';
    }
}

// 身份证号码清除
var idNoCancelBut = document.getElementById('idNo-cancel-but');
idNoCancelBut.onclick = function (e) {
    var idNoElem = document.getElementById('idNo');
    idNoElem.value = null;
    idNoElem = null
}
idNoCancelBut = null;

function createLoadingImage() {
    var loading = document.createElement('li');
    loading.id = 'loadingImgTmp';
    loading.style.display = 'block';
    loading.className = "weui-uploader__file weui-uploader__file_status";

    var div = document.createElement('div');
    div.className = "weui-uploader__file-content";

    var img = document.createElement('img');
    img.src = "/css/images/loading.gif";

    div.appendChild(img);
    loading.appendChild(div);
    return loading;
}

// 上传图片
function postFile(files, cb) {
    hideUploadBut(true);
    var file = files[0];
    var db = new FormData();
    db.append("Filedata", file);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", g_uploaderUrl);
    xhr.onload = function (e) {
        if (g_uploadNum < e_maxUpload) {
            hideUploadBut(false);
        }
        if (this.status !== 200) {
            console.error('上传图片返回错误');
            return cb('上传图片错误');
        }
        var json = JSON.parse(this.response);
        cb(null, json)
    }
    xhr.send(db);
}

function changeImageUrlsValue(key, value) {
    var urls = document.getElementById('imageUrls');
    var childrens = urls.children;
    var len = childrens.length;
    var i, item, url;
    for (i = 0; i < len; i++) {
        item = childrens[i];
        url = 'url("' + item.value + '")';
        // 根据url 查找匹配的项
        if (url === key) {
            item.value = value;
            break
        }
    }
}

function createShowImageLi(url) {
    var li = document.createElement('li');
    li.className = "weui-uploader__file weui-uploader__file_status";
    li.style['backgroundImage'] = 'url(' + url + ')';


    li.onclick = function () {
        var fileInput = document.getElementById('changeImage');
        var liThis = this;
        // 重新绑定onchange事件
        fileInput.onchange = function () {
            if (this.files.length === 0) {
                return;
            }
            // 隐藏li
            liThis.style.display = 'none';

            // 插入loading
            var ulElem = document.getElementById('uploaderFiles');
            var cloneLoading = createLoadingImage();
            ulElem.insertBefore(cloneLoading, liThis);

            postFile(this.files, function (err, json) {
                if (err) {
                    return showMsg('上传图片错误', function () {
                        liThis.style.display = 'initial';
                    });
                }
                //删除loading
                ulElem.removeChild(cloneLoading);
                cloneLoading = null;

                // 更改li的图片和显示
                liThis.style.display = 'initial';
                var originUrl = liThis.style['backgroundImage'];
                liThis.style['backgroundImage'] = 'url(' + json.url + ')';

                // 修改对应的提交item的值
                changeImageUrlsValue(originUrl, json.url);
            })
            fileInput = null;
        }
        fileInput.click();
    }
    return li;
}
function createHiddenInput(url) {
    var elem = document.createElement('input');
    elem.type = "hidden";
    elem.value = url;
    elem.name = 'image' + g_uploadNum;
    //li.style="display:none";
    return elem;
}

function hideUploadBut(hide) {
    var elem = document.getElementById('uploader');
    if (hide) {
        elem.style.display = 'none';
    } else {
        elem.style.display = 'block';
    }
}
function showLoading(show) {
    var img = document.getElementById('loadingImg');
    if (show) {
        img.style.display = 'block';
    } else {
        img.style.display = 'none';
    }
    img = null;
}

function afterUpload(ret) {
    // 插入上传的图片
    var liElem = createShowImageLi(ret.url);

    var ulElem = document.getElementById('uploaderFiles');
    var loadingElem = document.getElementById('loadingImg');
    ulElem.insertBefore(liElem, loadingElem);
    // ulElem.appendChild(liElem);
    ulElem = null;

    // 隐藏loading
    showLoading(false);

    // 插入image urls
    var inputElem = createHiddenInput(ret.url);
    var imageUrls = document.getElementById('imageUrls');

    imageUrls.appendChild(inputElem);
    imageUrls = null;

    g_uploadNum++;
    if (g_uploadNum === e_maxUpload) {
        // 隐藏上传按钮
        hideUploadBut(true);
        // 更新提交状态
        // if (isValidate()) {
        //     toggleSubmitStatus(true);
        // }
    }
}


var uploadElem = document.getElementById('uploaderInput');
uploadElem.onchange = function () {
    console.log("file change");
    if (g_uploadNum >= e_maxUpload) {
        console.error('max upload')
        return;
    }
    if (this.files.length === 0) {
        return;
    }
    showLoading(true);
    postFile(this.files, function (err, json) {
        if (err) {
            return showMsg('上传图片错误', function () {
                showLoading(false);
            });
        }
        afterUpload(json);
    })
}


// function bindCheck() {
//     var checkNodes = document.getElementsByClassName('check');
//     var i, item, len = checkNodes.length;
//     for (i = 0; i < len; i++) {
//         item = checkNodes[i];
//         item.onkeyup = function (e) {
//             var value = this.value;
//             var name = this.name;
//
//             if (this.value === "") {
//                 validateStatus[name] = false;
//                 toggleSubmitStatus(false);
//                 return
//             }
//             validateStatus[name] = true;
//             if (isValidate()) {
//                 toggleSubmitStatus(true);
//             }
//             //if idNo bind show cancel button
//             //console.log( "this.id:" +  this.id);
//             if (this.id === 'idNo') {
//                 toggleShowCancelBut(this.value);
//             }
//         }
//     }
// }

//bindCheck();

function showElement(elem) {
    document.getElementById(elem).style.display = "block";
}
function hideElement(elem) {
    document.getElementById(elem).style.display = "none";
}

function hideMsg() {
    hideElement('js_muck');
}

function showMsg(msg, fn) {
    showElement('js_muck');
    var msgElem = document.getElementById('msg');
    msgElem.textContent = msg;
    document.getElementById('js_ok').onclick = function () {
        hideMsg();
        if (fn != null) {
            fn.call(this);
        }
    }
}

// 绑定form的提交检测
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function () {
    var err = isNotValidate();
    if (err) {
        showMsg(err);
        return false
    } else {
        return true
    }
}

